﻿using System.ComponentModel;

namespace KeyboardCount
{
    public partial class HistoryForm : Form
    {
        public HistoryForm()
        {
            InitializeComponent();
            DialogResult = DialogResult.Cancel;
        }

        public string SelectedDate { get; private set; } = "";

        private BindingList<MyList> DataBind = new BindingList<MyList>();
        private void HistoryForm_Load(object sender, EventArgs e)
        {
            dataGridView1.DataSource = DataBind;
            InitData();
        }

        private void InitData()
        {
            var files = Directory.GetFiles(Application.StartupPath, "log-*.txt", SearchOption.AllDirectories);
            foreach (var file in files)
            {
                DataBind.Add(GetData(file));
            }
        }

        private MyList GetData(string fileName)
        {
            var file = new FileInfo(fileName);

            var text = File.ReadAllText(fileName);
            var keys = text.TrimEnd(Convert.ToChar(1)).Split(Convert.ToChar(1));
            var date = file.Name.Replace("log-", "").Replace(".txt", "");
            var year = date.Substring(0, 4);
            var month = date.Substring(4, 2);
            var day = date.Substring(6, 2);

            return new MyList() { Key = $"{year}-{month}-{day}", Value = keys.Length };
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0 && e.RowIndex >= 0)
            {
                SelectedDate = $"log-{DataBind[e.RowIndex].Key.Replace("-", "")}.txt";
                DialogResult = DialogResult.OK;
                Close();
            }
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView1_CellContentClick(sender, new DataGridViewCellEventArgs(0, e.RowIndex));
        }
    }
}
